package dk.wifiathome;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class wifiathomeFileHandler{
	//TODO This class must be made more generic, so that it can be reused in other projects! .. Gufle
	boolean mExternalStorageAvailable = false;
	boolean mExternalStorageWriteable = false;
	
	FileOutputStream fileOutputStream = null;
	OutputStreamWriter out = null;
	
	// Parrent is the instance that has control over this object. 
	Context Parrent = null;
	
	File FileAbsoluteLocation= null;
	
	wifiathomeFileHandler(Context parrent,String directory, String fileName, boolean xmlFile){
		FileAbsoluteLocation = new File(directory);
		FileAbsoluteLocation.mkdirs();
		FileAbsoluteLocation = new File(""+directory+fileName);
		Parrent = parrent;
		init(xmlFile);
	};
	
	/**
	 *  Init function initializes the ability to write to the external storage and checks if this is possible
	 */
	private void init(boolean xmlFile){
		
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    // We can read and write the media
		    mExternalStorageAvailable = mExternalStorageWriteable = true;
		    //Check to see if the file is pressent in the filesystem. if pressent do nothing.

	        if(!FileAbsoluteLocation.exists()){
	        	try {
					FileAbsoluteLocation.createNewFile();
					// if not create file and insert header
					if (xmlFile)
				    {
				    	try{			
							fileOutputStream = new FileOutputStream(FileAbsoluteLocation, true);
							out = new OutputStreamWriter(fileOutputStream);
							// write the header to the file
							String textInput = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "\n";
							out.write(textInput);
							out.close();
						}catch(IOException e) {
					        // Unable to create file, likely because external storage is
					        // not currently mounted.
							Toast.makeText(Parrent, "save failed, exception"+ e.toString(), Toast.LENGTH_LONG).show();
					        Log.w("ExternalStorage", "Error writing " + FileAbsoluteLocation, e);
					    }
				    }
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	        }
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    // We can only read the media
		    mExternalStorageAvailable = true;
		    mExternalStorageWriteable = false;
		} else {
		    // Something else is wrong. It may be one of many other states, but all we need
		    //  to know is we can neither read nor write
		    mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
	}
	
	public boolean writeToFile(String input){
		if (mExternalStorageAvailable && mExternalStorageWriteable)
		{
			try{			
				fileOutputStream = new FileOutputStream(FileAbsoluteLocation, true);
				out = new OutputStreamWriter(fileOutputStream);
				String textInput = input + "\n";
				out.write(textInput);
				out.close();
			}catch(IOException e) {
		        // Unable to create file, likely because external storage is
		        // not currently mounted.
				Toast.makeText(Parrent, "save failed, exception"+ e.toString(), Toast.LENGTH_LONG).show();
		        Log.w("ExternalStorage", "Error writing " + FileAbsoluteLocation, e);
		        return false;
			}
		}
		else
		{
			Toast.makeText(Parrent, "filestream not created", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	
	public boolean writeListElementToXMLFile(String name, double cellLocationLat, double cellLocationLong,  
				double gpsLocationLat, double gpsLocationLong){
		if (mExternalStorageAvailable && mExternalStorageWriteable)
		{
			try{			
				fileOutputStream = new FileOutputStream(FileAbsoluteLocation, true);
				out = new OutputStreamWriter(fileOutputStream);
				String textInput = "<ListElement>" + "\n" + 
				  "	Name="+ "\""+ name +"\" \n" +
				  "	CellLatitude=" + "\""+ cellLocationLat +"\" \n" +
				  "	CellLongtitude=" + "\""+ cellLocationLong +"\" \n" +
				  "	GpsLatitude=" + "\""+ gpsLocationLat +"\" \n" +
				  "	GpsLongtitude=" + "\""+ gpsLocationLong +"\" \n" +
				  "<\\ListElement>"+"\n";
				out.write(textInput);
				out.close();
			}catch(IOException e) {
		        // Unable to create file, likely because external storage is
		        // not currently mounted.
		        Log.w("ExternalStorage", "Error writing " + FileAbsoluteLocation, e);
		        return false;
			}
		}
		else
		{
			return false;
		}
		return true;
	}
	
	public boolean writeXMLFileHeaderToFile(){
	if (mExternalStorageAvailable && mExternalStorageWriteable)
	{
		try{			
			fileOutputStream = new FileOutputStream(FileAbsoluteLocation, false);
			out = new OutputStreamWriter(fileOutputStream);
			String textInput = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "\n";
			out.write(textInput);
			out.close();
		}catch(IOException e) {
	        // Unable to create file, likely because external storage is
	        // not currently mounted.
	        Log.w("ExternalStorage", "Error writing " + FileAbsoluteLocation, e);
	        return false;
		}
	}
	else
	{
		return false;
	}
	return true;
}
	/**
	 *  This Function will read from a file 
	 */
	public boolean readFromFile(){
		
		
		return true;
	}
	
	/**
	 *  This Function will read from a file at startup and populate the list
	 * @throws IOException 
	 */
	public ArrayList<listData> readFromXmlListFile() throws IOException {
		if (mExternalStorageAvailable && mExternalStorageWriteable)
		{
		    ArrayList<listData> array_list = new ArrayList<listData>();
			try {
				FileInputStream fstream = new FileInputStream(FileAbsoluteLocation);
			    // Get the object of DataInputStream
			    DataInputStream in = new DataInputStream(fstream);
			    BufferedReader br = new BufferedReader(new InputStreamReader(in));
			    String strLine = "";   
			    while ((strLine = br.readLine()) != null)   {
			        // check if the line is a list or something else
			    	if ( strLine.contains("<ListElement>") )
			    	{
			    	    double CellLat = -1;
		    			double CellLong = -1;
		    			double GpsLat = -1;
		    			double GpsLong = -1;
		    			String Name = "";
		    			boolean saveEntry = false;
		    			
			    		// get the next line and check if it is diffrent from <\ListElement>
			    		while ( (strLine = br.readLine()) != null && !strLine.contains("<\\ListElement>") ) 
			    		{	
			    			if (strLine.contains("Name"))
			    			{
			    				saveEntry=false;
			    				int first = strLine.indexOf("\"");
			    				int last = strLine.indexOf('\"', (first+1));
			    				if (first > -1 && last > -1)
			    				{
			    					saveEntry=true;
			    					Name = strLine.substring(first+1, last);
			    				}
			    			}
			    			
			    			if (strLine.contains("CellLatitude"))
			    			{
			    				saveEntry=false;
			    				int first = strLine.indexOf("\"");
			    				int last = strLine.indexOf('\"', (first+1));
			    				if (first > -1 && last > -1)
			    				{
			    					saveEntry=true;
			    					CellLat = Double.valueOf(strLine.substring(first+1, last));
			    				}
			    			}
			    			
			    			if (strLine.contains("CellLongtitude"))
			    			{
			    				saveEntry=false;
			    				int first = strLine.indexOf("\"");
			    				int last = strLine.indexOf('\"', (first+1));
			    				if (first > -1 && last > -1)
			    				{
			    					saveEntry=true;
			    					CellLong = Double.valueOf(strLine.substring(first+1, last));
			    				}
			    			}
			    			
			    			if (strLine.contains("GpsLatitude"))
			    			{
			    				saveEntry=false;
			    				int first = strLine.indexOf("\"");
			    				int last = strLine.indexOf('\"', (first+1));
			    				if (first > -1 && last > -1)
			    				{
			    					saveEntry=true;
			    					GpsLat = Double.valueOf(strLine.substring(first+1, last));
			    				}
			    			}
			    			
			    			if (strLine.contains("GpsLongtitude"))
			    			{
			    				saveEntry=false;
			    				int first = strLine.indexOf("\"");
			    				int last = strLine.indexOf('\"', (first+1));
			    				if (first > -1 && last > -1)
			    				{
			    					saveEntry=true;
			    					GpsLong = Double.valueOf(strLine.substring(first+1, last));
			    				}
			    			}
			    		}
			    		if(saveEntry){
			    			listData NewObjectToAdd = new listData();
			    			NewObjectToAdd.setWifiSpotName(Name);
				    		NewObjectToAdd.setWifiSpotCellInfo(CellLat, CellLong);
			    			NewObjectToAdd.setWifiSpotGpsInfo(GpsLat, GpsLong);
			    			array_list.add(NewObjectToAdd);
			    		}
			    	}
			    }
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return array_list;
		}
		return null;
	}
}
